package app.util.image.action
{
	import app.util.*;
	import app.util.image.calc.*;
	
	import flash.display.*;
	import flash.geom.*;
	
	public class BithresholdAction extends AbstractAction
	{
		private var invert:Boolean;
		private var min:Number;
		private var max:Number;
		
		public function setValue(v0:Number, v1:Number, v:Boolean):BithresholdAction
		{
			this.min = v0;
			this.max = v1;
			this.invert = v;	
			return this;
		}		
		
		public override function getDescription():String
		{
			return "Bithresholding (" + this.min.toFixed(0) + ", " + this.max.toFixed(0) + ")";
		}
		
		public override function getActionedBitmapData():BitmapData
		{
			var old:BitmapData = Mediator.getCurrentBitmapData();
			var w:int = old.width;
			var h:int = old.height;
			var ret:BitmapData = new BitmapData(old.width, old.height);
			
			for(var i:int = 0; i < w; i++)
			{
				for(var j:int = 0; j < h; j++)
				{
					var gray:uint = BMPUtility.calcGrayFromColor(old.getPixel(i, j));
					var black:Boolean = ((gray > this.max) || (gray < this.min));
					if(black)
					{
						ret.setPixel(i, j, (this.invert ? 0xffffffff : 0xff000000));
					}
					else
					{
						ret.setPixel(i, j, (this.invert ? 0xff000000 : 0xffffffff));
					} 
				}
			}
			
			return ret;
		}
	}
}